package com.zs.usc.token.local;

import com.zs.usc.vo.CurrentUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单实例环境令牌管理
 *
 * @author ZS
 */
public class LocalTokenManager extends TokenManager {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    // 令牌存储结构
    private final Map<String, DummyUser> tokenMap = new ConcurrentHashMap<>();

    @Override
    public void verifyExpired() {
        LocalDateTime now = LocalDateTime.now();
        for (Entry<String, DummyUser> entry : tokenMap.entrySet()) {
            String token = entry.getKey();
            DummyUser dummyUser = entry.getValue();
            // 当前时间大于过期时间
            if (now.compareTo(dummyUser.expired) > 0) {
                // 已过期，清除对应token
                tokenMap.remove(token);
                logger.debug("token : " + token + "已失效");
            }
        }
    }

    public void addToken(String token, CurrentUserInfo loginUser) {
        DummyUser dummyUser = new DummyUser();
        dummyUser.loginUser = loginUser;
        extendExpiredTime(dummyUser);
        tokenMap.putIfAbsent(token, dummyUser);
    }

    public void remove(String token) {
        tokenMap.remove(token);
    }


    public CurrentUserInfo validate(String token) {
        DummyUser dummyUser = tokenMap.get(token);
        if (dummyUser == null) {
            return null;
        }
        extendExpiredTime(dummyUser);
        return dummyUser.loginUser;
    }


    /**
     * 扩展过期时间
     *
     * @param dummyUser
     */
    private void extendExpiredTime(DummyUser dummyUser) {
        dummyUser.expired = LocalDateTime.now().plusSeconds(tokenTimeout);
    }

    // 复合结构体，含loginUser与过期时间expried两个成员
    private class DummyUser {
        private CurrentUserInfo loginUser;
        private LocalDateTime expired; // 过期时间
    }
}
